/*
 * @Description: 流程中心模型
 * @Author: seadon
 * @LastEditors: seadon
 * @Date: 2021-07-08 20:57:22
 * @LastEditTime: 2022-09-22 21:04:25
 */
import { Ref, ref, unref, ComputedRef, computed } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash'
import { i18n } from '@/locales'
import { apiInit } from '@/services'
import { isString, isDef } from '@/utils'
import { useLoading } from '@/hooks/useLoading'
import { ListTypeEnum, taskTypeEnum } from '@/constant/enums/processCenter'
import { IFetchListParams, ITaskType } from '../type'
import { useStore } from 'vuex'
const { $t: iTrans, locale } = i18n

import {
	taskType,
	typeFieldMaps,
	typeServiceMaps,
	typeTaskCountMaps,
	typeServiceStateMaps,
} from '../constant/processType'

export default function useModel(tenantDetail?: ComputedRef<Recordable<any>>) {
	const isRequesting = ref(false)
	const route = useRoute()
	const { $t } = i18n
	const api = apiInit()
	const defaultLoading = ref({ loading: false })
	const countDefaultLoading = ref({ loading: false })
	const taskDefaultLoading = ref({ loading: true })
	const total = ref() // 总条数
	const sessionActive = localStorage.getItem('activeProcessKey') || 'TodoTask'
	const activeTabRef = ref(sessionActive)
	const pageIndexRef = ref(1) // 当前页数
	const tabDefaultValue = localStorage.getItem('tabDefaultValue') || '{}'
	const pageSize =
		JSON.parse(tabDefaultValue)[unref(activeTabRef)]?.pageSize || 20
	const pageSizeRef = ref(pageSize) // 条数
	const totalTaskTypeRef: Ref<Recordable<string | number>> = ref({})
	const optionsListRef: Ref<Recordable<any>[]> = ref([])
	const checkedListRef: Ref<(string | number)[]> = ref([])
	// 是否渲染tab
	const isTab = ref(false)
	// 委托人
	const totalAgentTaskTypeRef: Ref<Recordable<string | number>> = ref({})
	const optionsAgentListRef: Ref<Recordable<any>[]> = ref([])
	const checkedAgentListRef: Ref<(string | number)[]> = ref([])
	// 列表数据
	const listDataRef: Ref<Recordable<any>[]> = ref([])
	const taskCountRef: Ref<readonly ITaskType[]> = ref(cloneDeep(taskType))

	// 竞签
	const doneType: any = ref('own')
	// 竞签代办 我的待办 标识
	const doneTaskTypes: any = {
		own: 'DoneTask',
		bid: 'bidDoneTask',
		agent: 'AgentDoneTask',
	}

	const { getLoading, setLoading } = useLoading(defaultLoading)
	const { getLoading: countLoading, setLoading: setCountLoading } =
		useLoading(countDefaultLoading)
	const { getLoading: taskLoading, setLoading: setTaskLoading } =
		useLoading(taskDefaultLoading)

	// 任务数量接口(代办任务数量、未读知会数量、已读知会数量、预计代办数量、代理代办任务数量、代理未读知会数量)
	const store = useStore()
	const fetchTaskCount = async (activeKey?: string) => {
		if (!localStorage.activeProcessKey) {
			setCountLoading(true)
		}
		const {
			code,
			data,
			message: infoTip,
		} = await api.default.CountTaskPrivateV2POST({})

		if (code === '000000') {
			taskCountRef.value = unref(taskCountRef)
				.filter(item => {
					switch (item.route_name) {
						case taskTypeEnum.ExpactTask:
							return unref(tenantDetail)?.tenant_auth?.forecase_task
						case taskTypeEnum.AgentTodo:
						case taskTypeEnum.AgentNotice:
							return !!(data as Recordable<number>)?.[
								typeFieldMaps[item.route_name]
							]
						default:
							return true
					}
				})
				.map(item => {
					const field = typeFieldMaps[item.route_name]
					let newItem = item

					if (field) {
						const taskCount = (data as Recordable<any>)[field]

						newItem = {
							...item,
							count: taskCount,
							// count: taskCount > 99 ? '99+' : taskCount,
						}
					}

					return newItem
				})

			activeTabRef.value =
				localStorage.activeProcessKey ??
				(route.params.name as string) ?? // 首页传参
				activeKey ?? // 传值
				// 缓存值
				unref(taskCountRef)?.filter(type => !type?.hidden)[0]?.route_name
		} else {
			message.error(infoTip ?? '')
		}
		setCountLoading(false)
		isTab.value = true
	}

	const setActiveTab = (activeKey: string) => {
		activeTabRef.value = activeKey
	}

	// 获取流程定义以及每个流程的任务数量
	const fetchApplyFilterList = async (type = '') => {
		let activeTab = cloneDeep(unref(activeTabRef))
		setTaskLoading(true)
		if (activeTabRef.value === taskTypeEnum.DoneTask) {
			activeTab = doneTaskTypes[doneType.value]
		}
		const taskCountService = typeTaskCountMaps[unref(activeTab)]

		const {
			code,
			data,
			message: infoTip,
		} = await (api.default as Recordable<any>)[taskCountService]({})

		// 重置数据
		let count = 0
		optionsListRef.value = []
		checkedListRef.value = []

		if (code === '000000') {
			data?.forEach((item: Recordable<any>) => {
				optionsListRef.value.push({
					text: item.process_name,
					value: item.process_key,
					count: item.count,
					// count: item.count > 99 ? '99+' : item.count,
				})
				count += item.count
				if (type) {
					unref(checkedListRef).push(item.process_key)
				}
			})
			unref(totalTaskTypeRef).text = $t(
				'pages.process.select.allProcesses',
				'全部流程'
			)
			unref(totalTaskTypeRef).count = count
			// unref(totalTaskTypeRef).count = count > 99 ? '99+' : count
		} else {
			message.error(infoTip ?? '')
		}
		setTaskLoading(false)
	}
	// 获取委托授权人和数数量
	const fetchCountAgentTask = async (params: object) => {
		const {
			code,
			data,
			message: infoTip,
		} = await (api.default as Recordable<any>).CountAgentTaskPrivateV2POST({
			payload: {
				page: {},
				query: params,
			},
		})
		if (code === '000000') {
			// 重置数据
			let count = 0
			optionsAgentListRef.value = []
			checkedAgentListRef.value = []
			data?.forEach((item: Recordable<any>) => {
				if(item.user){
					optionsAgentListRef.value.push({
						text: item.user.employee_name,
						value: item.user.employee_id,
						// count: item.count > 99 ? '99+' : item.count,
						count: item.count,
						user: item.user,
					})
					count += item.count
					unref(checkedAgentListRef).push(item.user.employee_id)
				}
			})
			unref(totalAgentTaskTypeRef).text = $t(
				'pages.process.select.allAgents',
				'全部委托人'
			)
			unref(totalAgentTaskTypeRef).count = count
			// unref(totalAgentTaskTypeRef).count = count > 99 ? '99+' : count
		} else {
			message.error(infoTip ?? '')
		}
	}
	// 我的知会 批量标为已读
	const batchAllReaded = async (params: object) => {
		const {
			code,
			data,
			message: infoTip,
		} = await (api.default as Recordable<any>).ReadAllNoticeTaskPrivateV2POST({
			payload: {
				page: {},
				query: params,
			},
		})
		if (code === '000000') {
			message.success(
				iTrans('pages.process.allReadSucTip', `成功将${data}条知会标记为已读`, {
					count: data,
				})
			)
			initProcessCenter()
		} else {
			message.error(infoTip)
		}
	}
	// 获取审批中的数量
	const applyCount = ref({})
	const fetchApplyCount = async (params: object) => {
		const {
			code,
			data,
			message: infoTip,
		} = await (
			api.default as Recordable<any>
		).CountApplicationTaskPrivateV2POST({
			payload: params,
		})
		if (code === '000000') {
			applyCount.value = data
		}
	}
	// const taskNoticeCount = ref({})
	const fetchTaskNoticeCount = async (params: object) => {
		const {
			code,
			data,
			message: infoTip,
		} = await (api.default as Recordable<any>).CountNoticeTaskPrivateV2POST({
			payload: params,
		})
		if (code === '000000') {
			applyCount.value = data
		}
	}
	// 我的已办 增加审批状态筛选
	const fetchDoneTaskCount = async (params: object) => {
		const {
			code,
			data,
			message: infoTip,
		} = await (
			api.default as Recordable<any>
		).CountCommandTypeTaskDoneTaskPrivateV2POST({
			payload: params,
		})
		if (code === '000000') {
			applyCount.value = data
		}
	}
	// 竞签已办，增加审批状态筛选
	const fetchBidDoneTaskCount = async (params: object) => {
		const {
			code,
			data,
			message: infoTip,
		} = await (
			api.default as Recordable<any>
		).CountCommandTypeCompetitionDoneTaskPrivateV2POST({
			payload: params,
		})
		if (code === '000000') {
			applyCount.value = data
		}
	}
	// 代理已办 增加审批状态筛选
	const fetchAgentDoneTaskCount = async (params: object) => {
		const {
			code,
			data,
			message: infoTip,
		} = await (
			api.default as Recordable<any>
		).CountCommandTypeAgentDoneTaskPrivateV2POST({ payload: params })
		if (code === '000000') {
			applyCount.value = data
		}
	}

	const checkedId = computed(() =>
		unref(activeTabRef) === taskTypeEnum.TodoTask ||
		unref(activeTabRef) === taskTypeEnum.AgentTodo
			? 'task_instance_id'
			: unref(activeTabRef) === taskTypeEnum.Drafts
			? 'draft_id'
			: 'process_instance_id'
	)
	const selectedRows: any = ref([])
	let selectStateIds: any = []
	const titleCheckAll = ref(false)
	const titleIndeterminate = ref(false)
	const titleDisabled = ref(false)

	// 获取列表数据
	const fetchTableList = async ({
		queryInfo = {},
		isFirst = true,
		isReset = true,
	}: // listType = ListTypeEnum.TODO,
	IFetchListParams) => {
		isRequesting.value = true
		// 拷贝当前Tab值并返回，用作比对标识
		let activeTab = cloneDeep(unref(activeTabRef))
		let query = queryInfo
		if (!query.status) query.status = 'approve'
		listDataRef.value = []
		store.state[typeServiceStateMaps[activeTab]].data = []
		if (isFirst) {
			pageIndexRef.value = 1
			const tabDefaultValue = localStorage.getItem('tabDefaultValue') || '{}'
			const pageSize =
				JSON.parse(tabDefaultValue)[unref(activeTabRef)]?.pageSize || 20
			pageSizeRef.value = pageSize
			isReset && (listDataRef.value = [])
		} else if (unref(getLoading)) {
			return
		}

		if (activeTab === taskTypeEnum.Drafts) {
			query = {
				name: queryInfo?.subject,
				time_sort: queryInfo.time_sort || 'desc',
			}
		}
		setLoading(true)
		if (activeTab === taskTypeEnum.DoneTask) {
			activeTab = doneTaskTypes[doneType.value]
			let localMerge = localStorage.getItem('subjectChecked')
			query = {
				...query,
				merge_task_flag: localMerge
					? localMerge == 'true'
						? true
						: false
					: false,
			}
		}
		if (activeTab === taskTypeEnum.TodoTask) {
			let localMerge: any = localStorage.getItem('authority')
			query = {
				...query,
				merge_task_flag: JSON.parse(localMerge)
					? localMerge == 'true'
						? true
						: false
					: false,
			}
		}
		const requestParams = {
			page: {
				page_index: unref(pageIndexRef),
				page_size: unref(pageSizeRef),
			},
			query,
		}
		let taskService = typeServiceMaps[activeTab]
		if (isDef(taskService) && !isString(taskService)) {
			taskService =
				taskService[queryInfo.listType] || taskService[ListTypeEnum.TODO]
		}
		const {
			code,
			data,
			message: infoTip,
		} = await (api.default as Recordable<any>)[taskService]({
			payload: requestParams,
		})
		setLoading(false)
		if (code === '000000') {
			// 整理当前负责人数据
			if (taskTypeEnum.ExpactTask === activeTab) {
				data.rows = data.rows.map((row: Recordable<any>) => {
					const currentManagers: Recordable<any>[] = []
					const currentNodeMessage: Recordable<any>[] = cloneDeep(
						row.current_node_message
					)
					currentNodeMessage?.forEach(node => {
						currentManagers.push(...node.identity_users)
					})
					row.task_assignee_list = currentManagers.map(user => {
						if (user === null) {
							return {}
						}
						return user
					})
					return row
				})
			}
			selectedRows.value = []
			selectedRows.value = data.rows.filter((item: any) => {
				return selectStateIds.indexOf(item[checkedId.value]) > -1
			})
			selectStateIds = []
			listDataRef.value = data.rows.map((item: any) => {
				const hasSelectRow: any = selectedRows.value.find(
					(selectItem: any) =>
						selectItem[unref(checkedId)] == item[unref(checkedId)]
				)

				// 设置checked
				item.checked = false
				if (hasSelectRow) {
					item.checked = true
					const flagss = selectedRows.value.find(
						(selectItem: any) =>
							selectItem[unref(checkedId)] == item[unref(checkedId)]
					)
					if (!flagss) {
						selectedRows.value.push(item)
					}
				}

				// 设置disabled
				item.disable = false
				if (
					(unref(activeTabRef) === taskTypeEnum.AgentTodo &&
						!item.allow_batch_approval) ||
					(unref(activeTabRef) === taskTypeEnum.TodoTask &&
						!item.allow_batch_approval)
				) {
					item.disable = true
					item.checked = false
				}

				return item
			})
			const noDisableData = listDataRef.value.filter(
				(item: any) => !item.disable
			)
			titleDisabled.value = !noDisableData.length
			if (
				selectedRows.value.length &&
				selectedRows.value.length >= noDisableData.length
			) {
				// 当前页全部选中
				titleCheckAll.value = true
				titleIndeterminate.value = false
			} else if (selectedRows.value && !selectedRows.value.length) {
				// 无一选中
				titleCheckAll.value = false
				titleIndeterminate.value = false
			} else {
				// 部分选中
				titleCheckAll.value = false
				titleIndeterminate.value = true
			}
			// 判断当前页是否全部选中
			// selectedRows

			// 判断是否选中一部分
			store.state[typeServiceStateMaps[activeTab]].total = data.page.total
			if (queryInfo?.status === 'approve') {
				store.commit('setTaskCount', { approve: data.page.total })
			}
			store.state[typeServiceStateMaps[activeTab]].data = listDataRef.value
			isRequesting.value = false
			// store.state[typeServiceStateMaps[activeTab]].data = []
		} else {
			message.error(infoTip ?? '')
		}
	}

	// 已办类型改变
	const doneTypesChange = () => {
		// fetchTableList()
		initProcessCenter('', {
			time_sort: 'desc',
			...{},
			type_key_list: store.state.firterAfterDate['DoneTask'][unref(doneType)]
				? store.state.firterAfterDate['DoneTask'][unref(doneType)].join(',')
				: '',
		})
	}

	// 批量同意操作
	const batchAgree = async (
		selectedRows: Recordable<any>[],
		type: string,
		resolve: any,
		reject: any
	) => {
		let url = 'BatchApprovalTaskPrivateV2POST'
		if (type === 'AgentTodo') {
			url = 'BatchApprovalAgentTaskPrivateV2POST'
		}
		const {
			code,
			data,
			message: infoTip,
		} = await api.default[
			url as
				| 'BatchApprovalTaskPrivateV2POST'
				| 'BatchApprovalAgentTaskPrivateV2POST'
		]({
			payload: selectedRows.map(item => ({
				task_instance_id: item.task_instance_id,
				agent_id: item?.consigner?.employee_id || item?.agent_id,
			})),
		})

		if (code === '000000') {
			resolve?.()
			return data
		} else {
			message.error(infoTip ?? '')
			reject?.()
			return false
		}
	}

	// 草稿箱删除
	const deleteDraft = async (
		draft_list: typing.DraftParam['draft_list'],
		resolve: any,
		reject: any
	) => {
		const {
			code,
			data,
			message: infoTip,
		} = await api.default.DeleteDraftPrivateV2POST({
			payload: { draft_list },
		})

		if (code === '000000') {
			if (data) {
				message.success($t('pages.process.tip.deleteSuccess', '删除成功'))
				resolve?.()
			} else {
				message.error($t('pages.process.tip.failTip', '操作失败'))
				reject?.()
			}
			return data
		} else {
			message.error(infoTip ?? '')
			reject?.()
			return false
		}
	}

	// 初始化流程中心
	const initProcessCenter = async (
		activeKey?: string,
		queryInfo: Recordable<any> = {}
	) => {
		setLoading(true)
		// 其它接口依赖于Count接口
		// await fetchTaskCount(activeKey)
		fetchTaskCount(activeKey)
		fetchApplyFilterList()
		if (unref(activeTabRef) === taskTypeEnum.Apply) {
			fetchApplyCount(queryInfo)
		}
		if (unref(activeTabRef) === taskTypeEnum.TaskNotice) {
			fetchTaskNoticeCount(queryInfo)
		}
		if (unref(activeTabRef) === taskTypeEnum.DoneTask) {
			unref(doneType) === 'own'
				? fetchDoneTaskCount(queryInfo)
				: unref(doneType) === 'bid'
				? fetchBidDoneTaskCount(queryInfo)
				: fetchAgentDoneTaskCount(queryInfo)
		}
		fetchTableList({ queryInfo, listType: queryInfo.listType })
	}
	const updatePageIndex = (index: number) => {
		pageIndexRef.value = index
	}

	const titleChange = (value: any) => {
		titleCheckAll.value = value.target.checked
		titleIndeterminate.value = false
		listDataRef.value = listDataRef.value.map((item: any) => {
			item.checked = value.target.checked && !item.disable
			return item
		})
		if (titleCheckAll.value) {
			selectedRows.value = cloneDeep(
				listDataRef.value.filter((item: any) => !item.disable)
			)
		} else {
			selectedRows.value = []
		}
	}
	const newArr = []
	const onChange = (record: any) => {
		if (record.checked) {
			selectedRows.value.push(record)
		} else {
			selectedRows.value.splice(
				selectedRows.value.findIndex(
					(item: any) => item[checkedId.value] === record[checkedId.value]
				),
				1
			)
		}
		const noDisableData = listDataRef.value.filter((item: any) => !item.disable)
		// 已选中的数量 当时table数量对比
		if (
			selectedRows.value &&
			selectedRows.value.length >= noDisableData.length
		) {
			// 当前页全部选中
			titleCheckAll.value = true
			titleIndeterminate.value = false
		} else if (selectedRows.value && !selectedRows.value.length) {
			// 无一选中
			titleCheckAll.value = false
			titleIndeterminate.value = false
		} else {
			// 部分选中
			titleCheckAll.value = false
			titleIndeterminate.value = true
		}
	}
	const handleClearSelect = () => {
		selectedRows.value = []
		const obj = {
			target: false,
		}
		titleChange(obj)
	}
	// 设置选择列
	const handleSetSelectState = (selectArr: []) => {
		selectStateIds = []
		const resultDataArr = selectArr.map((item: any) => {
			return item[unref(checkedId)]
		})
		selectStateIds = resultDataArr
		// selectedRows.value = resultDataArr
	}
	// 改变是否按照流程实例进行合并
	const changeMergeChecked = (status: any) => {
		localStorage.setItem('subjectChecked', `${status}`)
	}
	return {
		pageIndexRef,
		pageSizeRef,
		total,
		getLoading,
		taskLoading,
		countLoading,
		listDataRef,
		taskCountRef,
		checkedListRef,
		optionsListRef,
		totalTaskTypeRef,
		totalAgentTaskTypeRef,
		optionsAgentListRef,
		checkedAgentListRef,
		applyCount,
		// taskNoticeCount,
		getActiveTab: activeTabRef,
		isTab,
		titleCheckAll,
		titleIndeterminate,
		titleDisabled,
		selectedRows,
		titleChange,
		setActiveTab,
		setTaskLoading,
		batchAgree,
		deleteDraft,
		initProcessCenter,
		fetchTableList,
		fetchTaskCount,
		fetchApplyFilterList,
		fetchCountAgentTask,
		updatePageIndex,
		fetchApplyCount,
		fetchTaskNoticeCount,
		fetchDoneTaskCount,
		fetchBidDoneTaskCount,
		onChange,
		handleClearSelect,
		handleSetSelectState,
		batchAllReaded,
		doneTypesChange,
		doneType,
		isRequesting,
		changeMergeChecked,
		fetchAgentDoneTaskCount,
	}
}
